//
//  UserAccount.swift
//  weibo1
//
//  Created by changhongliang on 2017/7/25.
//  Copyright © 2017年 richinfo. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    /// 用于调用access_token,接口获取授权后的access_token
    var access_token:String?
    /// access_token的生命周期，单位为秒
    var expires_in :NSNumber?{
        didSet{
            expires_Date = NSDate(timeIntervalSinceNow: expires_in!.doubleValue)
        }
    }
    
    ///过期时间(年月日时分秒)
    var expires_Date:NSDate?
    ///当前授权用户的UID。
    var uid:String?
    
    ///用户昵称
    var screen_name:String?
    //用户头像
    var avatar_large:String?
    
    static var userAccount: UserAccount?
    
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeys(dict)
    }
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    override var description: String{
        let property = ["access_token","expires_in","uid","screen_name","avatar_large"]
        let dic = dictionaryWithValues(forKeys: property)
        return "\(dic)"
    }
    
    static let filePath = "userAccount.plist".cacheDir()
    
    /// MARK: - 外部控制方法
    ///保存授权模型到文件中
    func saveAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile:UserAccount.filePath)
    }
    
     /// 从文件中读取保存的授权模型
    class func loadUserAccount() -> UserAccount? {
        if userAccount != nil {
            return userAccount
        }
        userAccount = NSKeyedUnarchiver.unarchiveObject(withFile:UserAccount.filePath)as?UserAccount
        if let date = userAccount?.expires_Date {
            if date.compare(Date()) == ComparisonResult.orderedDescending {
                userAccount = nil
                HLLog("登录过期了")
                return userAccount
            }
        }
        return userAccount
    }
    
    ///判断是否已经登录
    class func login() -> Bool {
        return UserAccount.loadUserAccount() != nil
    }
    
    //MARK: - NSCoding 
    //解档
    required init?(coder aDecoder: NSCoder){
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expires_in = aDecoder.decodeObject(forKey: "expires_in") as? NSNumber
        uid = aDecoder.decodeObject(forKey: "uid") as? String
        screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
        avatar_large = aDecoder.decodeObject(forKey:"avatar_large")as? String
    }
    
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(screen_name, forKey:"screen_name")
        aCoder.encode(avatar_large, forKey:"avatar_large")
    }
    
}
